package main

import (
	"boke/blogpb"
	"context"
	"fmt"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// 接收删除博客请求
func (s *server) DeleteBlog(ctx context.Context, req *blogpb.DeleteBlogRequest) (b *blogpb.DeleteBlogResponse, err error) {
	fmt.Println("接收删除blog请求 delete blog request")

	blogreqid := req.GetBlogId()

	// 1. 查出对象
	blog_item := &blogItem{}
	err = db.Get(blog_item, select_sql, blogreqid)

	if err != nil {
		return nil, status.Errorf(
			codes.Internal,
			fmt.Sprintf("Cannot select object in MySQL: %v", err),
		)
	}

	if blog_item.Title == "" {
		return nil, status.Errorf(
			codes.NotFound,
			fmt.Sprintf("Cannot find blog in MySQL: %v", err),
		)
	}
	_, err = db.Exec(delete_sql, blogreqid)

	if err != nil {
		return nil, status.Errorf(
			codes.Internal,
			fmt.Sprintf("Cannot delete object in MySQL: %v", err),
		)
	}

	return &blogpb.DeleteBlogResponse{BlogId: req.GetBlogId()}, nil

}
